package com.jdls.web;

import com.jdls.pojo.Book;
import com.jdls.pojo.Result;
import com.jdls.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 嘉德罗斯
 * @date 2021/9/15
 */

//等同于@Controller和@ResponseBody两个注解的组合
@RestController
//配置模块的公共映射
@RequestMapping("book")
public class BookWeb {
    //自动装配
    @Autowired
    private BookService bookService;

    @PostMapping
    public Result add(@RequestBody Book book) {
        Integer i = bookService.add(book);
        Method method = new Method(i).invoke();
        boolean flag = method.isFlag();
        String msg = method.getMsg();
        return new Result(flag,flag,msg);
    }
    @PutMapping
    public Result update(@RequestBody Book book) {
        Integer i = bookService.update(book);
        Method method = new Method(i).invoke();
        boolean flag = method.isFlag();
        String msg = method.getMsg();
        return new Result(flag,flag,msg);
    }

    @DeleteMapping("{id}")
    public Result delete(/*获取路径参数*/@PathVariable int id) {
        Integer i = bookService.delete(id);
        Method method = new Method(i).invoke();
        boolean flag = method.isFlag();
        String msg = method.getMsg();
        return new Result(flag,flag,msg);
    }
    @GetMapping
    public Result findAll() {
        //int a = 1/0;
        List<Book> all = bookService.findAll();
        boolean flag;
        String msg ;
        if (all!=null){
            flag = true;
            msg = "";
        }else {
            flag = false;
            msg = "你的操作有误";
        }
        return new Result(all,flag,msg);
    }
    @GetMapping("{id}")
    public Result findById(@PathVariable int id) {
        Book all = bookService.findById(id);
        boolean flag;
        String msg ;
        if (all!=null){
            flag = true;
            msg = "";
        }else {
            flag = false;
            msg = "你的操作有误";
        }
        return new Result(all,flag,msg);
    }

    private class Method {
        private Integer i;
        private boolean flag;
        private String msg;

        public Method(Integer i) {
            this.i = i;
        }

        public boolean isFlag() {
            return flag;
        }

        public String getMsg() {
            return msg;
        }

        public Method invoke() {
            if (i>0){
                flag = true;
                msg = "";
            }else {
                flag = false;
                msg = "你的操作有误";
            }
            return this;
        }
    }
}
